package me.learningandroid.ch3_2.sqlitedemo;

import android.icu.text.DateFormat;
import android.icu.text.SimpleDateFormat;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import java.util.List;

public class TodoItemAdaptor extends RecyclerView.Adapter<TodoItemAdaptor.ViewHolder> {
    private List<TodoEntity> data;
    private CompoundButton.OnCheckedChangeListener checkBoxListener;
    private View.OnClickListener deleteListener;

    public TodoItemAdaptor(@NonNull List<TodoEntity> data, CompoundButton.OnCheckedChangeListener checkBoxListener, View.OnClickListener deleteListener) {
        this.data = data;
        this.checkBoxListener = checkBoxListener;
        this.deleteListener = deleteListener;
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item, parent, false);

        CheckBox checkBox = view.findViewById(R.id.checkbox);
        Button btnDelete = view.findViewById(R.id.btnDelete);
        checkBox.setOnCheckedChangeListener(checkBoxListener);
        btnDelete.setOnClickListener(deleteListener);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        TodoEntity todoEntity = data.get(position);
        holder.textViewContent.setText(todoEntity.content);
        holder.checkBox.setOnCheckedChangeListener(null);
        holder.checkBox.setChecked(todoEntity.done!=0);
        holder.checkBox.setOnCheckedChangeListener(checkBoxListener);
        holder.btnDelete.setTag(todoEntity.id);
        holder.checkBox.setTag(todoEntity.id);
    }

    @Override
    public int getItemCount() {
        return data.size();
    }

    public static class ViewHolder extends RecyclerView.ViewHolder {
        private CheckBox checkBox;
        private TextView textViewContent;
        private Button btnDelete;
        public ViewHolder(@NonNull View itemView) {
            super(itemView);
            checkBox = itemView.findViewById(R.id.checkbox);
            textViewContent = itemView.findViewById(R.id.textViewContent);
            btnDelete = itemView.findViewById(R.id.btnDelete);
        }
    }
}
